///////////////////////////////////////////////////////////////////////////////
// Name:        ax_pagerctrl.cpp
// Purpose:     AxPagerCtrl: a book with no controller
// Author:      Julian Smart
// Modified by:
// Created:     2008-05-29
// RCS-ID:      $Id$
// Copyright:   (c) 2003 Vadim Zeitlin <vadim@wxwidgets.org>
//              (c) 2008 Julian Smart
// Licence:     New BSD License
///////////////////////////////////////////////////////////////////////////////

// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

#include "wx/wx.h"
#include "wx/settings.h"

#include "ax/ax_pagerctrl.h"

// ============================================================================
// implementation
// ============================================================================

// ----------------------------------------------------------------------------
// event table
// ----------------------------------------------------------------------------

IMPLEMENT_ABSTRACT_CLASS(AxPagerCtrl, wxControl)

BEGIN_EVENT_TABLE(AxPagerCtrl, wxControl)
    EVT_SIZE(AxPagerCtrl::OnSize)
    EVT_PAINT(AxPagerCtrl::OnPaint)
    EVT_ERASE_BACKGROUND(AxPagerCtrl::OnEraseBackground)
#if wxUSE_HELP
    EVT_HELP(wxID_ANY, AxPagerCtrl::OnHelp)
#endif // wxUSE_HELP
END_EVENT_TABLE()

// ----------------------------------------------------------------------------
// constructors and destructors
// ----------------------------------------------------------------------------

void AxPagerCtrl::Init()
{
    m_fitToCurrentPage = false;

    m_internalBorder = 0;
    m_controlMargin = 0;
    m_controlSizer = NULL;
    m_selection = -1;
    m_topRuleSize = 2;
    m_drawTopRule = false;
}

bool
AxPagerCtrl::Create(wxWindow *parent,
                       wxWindowID id,
                       const wxPoint& pos,
                       const wxSize& size,
                       long style,
                       const wxString& name)
{
    if (!wxControl::Create
                     (
                        parent,
                        id,
                        pos,
                        size,
                        style,
                        wxDefaultValidator,
                        name
                     ))
        return false;

    SetBackgroundStyle(wxBG_STYLE_CUSTOM);

    return true;
}

AxPagerCtrl::~AxPagerCtrl()
{
}

// ----------------------------------------------------------------------------
// geometry
// ----------------------------------------------------------------------------

void AxPagerCtrl::DoInvalidateBestSize()
{
    wxControl::InvalidateBestSize();
}

void AxPagerCtrl::SetPageSize(const wxSize& size)
{
    SetClientSize(CalcSizeFromPage(size));
}

wxSize AxPagerCtrl::CalcSizeFromPage(const wxSize& sizePage) const
{
    wxSize size = sizePage;
#if 0
    if ( IsVertical() )
    {
        size.y += GetInternalBorder();
    }
    else // left/right aligned
    {
        size.x += GetInternalBorder();
    }
#endif

    if (GetDrawTopRule())
        size.y += GetTopRuleSize();

    return size;
}

wxSize AxPagerCtrl::DoGetBestSize() const
{
    wxSize bestSize;

    // iterate over all pages, get the largest width and height
    const size_t nCount = m_pages.size();
    for ( size_t nPage = 0; nPage < nCount; nPage++ )
    {
        const wxWindow * const pPage = m_pages[nPage];
        if( pPage )
        {
            wxSize childBestSize(pPage->GetBestSize());

            if ( childBestSize.x > bestSize.x )
                bestSize.x = childBestSize.x;

            if ( childBestSize.y > bestSize.y )
                bestSize.y = childBestSize.y;
        }
    }

    if (m_fitToCurrentPage && GetCurrentPage())
        bestSize = GetCurrentPage()->GetBestSize();

    // convert display area to window area, adding the size necessary for the
    // tabs
    wxSize best = CalcSizeFromPage(bestSize);
    CacheBestSize(best);
    return best;
}

wxRect AxPagerCtrl::GetPageRect() const
{
    wxRect rectPage(wxPoint(0,0), GetClientSize());

    if (GetDrawTopRule())
    {
        rectPage.y = GetTopRuleSize();
        rectPage.height -= GetTopRuleSize();
    }

    return rectPage;
}

// Lay out controls
void AxPagerCtrl::DoSize()
{
    if (GetSizer())
        Layout();

    // resize all pages to fit the new control size
    const wxRect pageRect = GetPageRect();
    const unsigned pagesCount = m_pages.Count();
    for ( unsigned int i = 0; i < pagesCount; ++i )
    {
        wxWindow * const page = m_pages[i];
        if ( !page )
        {
            wxASSERT_MSG( AllowNullPage(),
                _T("Null page in a control that does not allow null pages?") );
            continue;
        }

        page->SetSize(pageRect);
    }
}

void AxPagerCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
{
    // event.Skip();

    DoSize();
}

void AxPagerCtrl::OnPaint(wxPaintEvent& WXUNUSED(event))
{
    wxPaintDC dc(this);

    if (GetDrawTopRule())
    {
        wxSize clientSize(GetClientSize());
        wxPen pen1(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW));
        wxPen pen2(wxSystemSettings::GetColour(wxSYS_COLOUR_3DDKSHADOW));

        dc.SetPen(pen1);
        dc.DrawLine(0, 0, clientSize.x, 0);

        dc.SetPen(pen2);
        dc.DrawLine(0, 1, clientSize.x, 1);
    }
}

void AxPagerCtrl::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
{
}

// ----------------------------------------------------------------------------
// miscellaneous stuff
// ----------------------------------------------------------------------------

#if wxUSE_HELP

void AxPagerCtrl::OnHelp(wxHelpEvent& event)
{
    // determine where does this even originate from to avoid redirecting it
    // back to the page which generated it (resulting in an infinite loop)

    // notice that we have to check in the hard(er) way instead of just testing
    // if the event object == this because the book control can have other
    // subcontrols inside it (e.g. wxSpinButton in case of a notebook in wxUniv)
    wxWindow *source = wxStaticCast(event.GetEventObject(), wxWindow);
    while ( source && source != this && source->GetParent() != this )
    {
        source = source->GetParent();
    }

    if ( source && m_pages.Index(source) == wxNOT_FOUND )
    {
        // this event is for the book control itself, redirect it to the
        // corresponding page
        wxWindow *page = NULL;

        if ( event.GetOrigin() == wxHelpEvent::Origin_HelpButton )
        {
            // show help for the page under the mouse
            const int pagePos = HitTest(ScreenToClient(event.GetPosition()));

            if ( pagePos != wxNOT_FOUND)
            {
                page = GetPage((size_t)pagePos);
            }
        }
        else // event from keyboard or unknown source
        {
            // otherwise show the current page help
            page = GetCurrentPage();
        }

        if ( page )
        {
            // change event object to the page to avoid infinite recursion if
            // we get this event ourselves if the page doesn't handle it
            event.SetEventObject(page);

            if ( page->GetEventHandler()->ProcessEvent(event) )
            {
                // don't call event.Skip()
                return;
            }
        }
    }
    //else: event coming from one of our pages already

    event.Skip();
}

#endif // wxUSE_HELP

// ----------------------------------------------------------------------------
// pages management
// ----------------------------------------------------------------------------

bool
AxPagerCtrl::InsertPage(size_t nPage,
                           wxWindow *page,
                           const wxString& text,
                           bool bSelect,
                           int WXUNUSED(imageId))
{
    wxCHECK_MSG( page || AllowNullPage(), false,
                 _T("NULL page in AxPagerCtrl::InsertPage()") );
    wxCHECK_MSG( nPage <= m_pages.size(), false,
                 _T("invalid page index in AxPagerCtrl::InsertPage()") );

    m_pageLabels.Insert(text, nPage);
    m_pages.Insert(page, nPage);

    if ( page )
        page->SetSize(GetPageRect());

    if (bSelect)
    {
        m_selection = nPage;
    }
    else
        page->Hide();

    DoInvalidateBestSize();

    return true;
}

bool AxPagerCtrl::DeletePage(size_t nPage)
{
    wxWindow *page = DoRemovePage(nPage);
    if ( !(page || AllowNullPage()) )
        return false;

    // delete NULL is harmless
    delete page;

    return true;
}

wxWindow *AxPagerCtrl::DoRemovePage(size_t nPage)
{
    wxCHECK_MSG( nPage < m_pages.size(), NULL,
                 _T("invalid page index in AxPagerCtrl::DoRemovePage()") );

    wxWindow *pageRemoved = m_pages[nPage];
    m_pages.RemoveAt(nPage);
    m_pageLabels.RemoveAt(nPage);
    DoInvalidateBestSize();

    return pageRemoved;
}

int AxPagerCtrl::GetNextPage(bool forward) const
{
    int nPage;

    int nMax = GetPageCount();
    if ( nMax-- ) // decrement it to get the last valid index
    {
        int nSel = GetSelection();

        // change selection wrapping if it becomes invalid
        nPage = forward ? nSel == nMax ? 0
                                       : nSel + 1
                        : nSel == 0 ? nMax
                                    : nSel - 1;
    }
    else // notebook is empty, no next page
    {
        nPage = wxNOT_FOUND;
    }

    return nPage;
}

int AxPagerCtrl::GetSelection() const
{
    return m_selection;
}


int AxPagerCtrl::DoSetSelection(size_t n, int flags)
{
    wxCHECK_MSG( n < GetPageCount(), wxNOT_FOUND,
                 wxT("invalid page index in AxPagerCtrl::DoSetSelection()") );

    const int oldSel = GetSelection();

    if ( n != (size_t)oldSel )
    {
        wxBookCtrlBaseEvent *event = CreatePageChangingEvent();
        bool allowed = false;

        if ( flags & SetSelection_SendEvent )
        {
            event->SetSelection(n);
            event->SetOldSelection(oldSel);
            event->SetEventObject(this);

            allowed = !GetEventHandler()->ProcessEvent(*event) || event->IsAllowed();
        }

        if ( !(flags & SetSelection_SendEvent) || allowed)
        {
            if ( oldSel != wxNOT_FOUND )
                m_pages[oldSel]->Hide();

            wxWindow *page = m_pages[n];
            page->SetSize(GetPageRect());
            page->Show();
            page->SetFocus();

            // change selection now to ignore the selection change event
            UpdateSelectedPage(n);

            if ( flags & SetSelection_SendEvent )
            {
                // program allows the page change
                MakeChangedEvent(*event);
                (void)GetEventHandler()->ProcessEvent(*event);
            }
        }

        delete event;
    }

    return oldSel;
}

wxBookCtrlBaseEvent* AxPagerCtrl::CreatePageChangingEvent() const
{
    return new wxNotebookEvent(wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING, m_windowId);
}

void AxPagerCtrl::MakeChangedEvent(wxBookCtrlBaseEvent &event)
{
    event.SetEventType(wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED);
}

void AxPagerCtrl::UpdateSelectedPage(size_t newsel)
{
    m_selection = newsel;
}

bool AxPagerCtrl::SetPageText(size_t n, const wxString& strText)
{
    m_pageLabels[n] = strText;
    return true;
}

wxString AxPagerCtrl::GetPageText(size_t n)
{
    return m_pageLabels[n];
}

// Find the index for the given page (JACS)
int AxPagerCtrl::FindPage(wxWindow* window) const
{
    for ( unsigned int i = 0; i < GetPageCount(); ++i )
    {
        wxWindow * const page = m_pages[i];
        if (page == window)
            return i;
    }
    return -1;
}

// Find the index for the given page label (JACS)
int AxPagerCtrl::FindPage(const wxString& label) const
{
    for ( unsigned int i = 0; i < GetPageCount(); ++i )
    {
        if (m_pageLabels[i] == label)
            return i;
    }
    return -1;
}

// Find the window for the given page label (JACS)
wxWindow* AxPagerCtrl::FindPageWindow(const wxString& label) const
{
    int page = FindPage(label);
    if (page != -1)
        return GetPage(page);
    else
        return NULL;
}

